package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.beancontext.BeanContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;
import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    private void getBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        isLike(blog);
    }

    //查询当前用户是否点赞
    private void isLike(Blog blog) {
        //1.获取当前登录用户id
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //当前用户未登录，无需查询是否点赞
            return;
        }
        String key = BLOG_LIKED_KEY + blog.getId();
        Long userId = user.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null) {
            //当前用户已经点赞
            blog.setIsLike(true);
        } else {
            //当前用户没有点赞
            blog.setIsLike(false);
        }
    }

    /**
     * 查询热点数据
     *
     * @param current
     * @return
     */
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(this::getBlogUser);
        return Result.ok(records);
    }

    /**
     * 根据blog的id查询blog具体信息
     *
     * @param id
     * @return
     */
    public Result queryBlogById(Long id) {
        //1.获取笔记信息
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("该笔记不存在");
        }
        //2.获取用户信息
        getBlogUser(blog);

        //3.查看当前用户是否点赞
        isLike(blog);

        //返回
        return Result.ok(blog);
    }

    /**
     * 实现点赞---使用redis的SortedSet缓存点赞用户id
     *
     * @param id
     * @return
     */
    public Result updateLike(Long id) {
        //1.获取当前登录用户id
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //当前用户未登录，不可点赞
            return Result.fail("您还没有登录，不可点赞");
        }
        Long userId = user.getId();
        //2.判断当前登录用户是否点赞
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null) {
            //3.当前用户已经点赞
            //3.1数据库点赞数减一
            boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
            if (success) {
                //3.2跟新redis的数据
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        } else {
            //3.当前用户未点赞
            //3.1数据库点赞数加一
            boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
            if (success) {
                //3.2跟新redis的数据
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }

        return Result.ok();
    }

    /**
     * 查询点赞过该blog的用户
     *
     * @param id
     * @return
     */
    public Result queryBlogLikes(Long id) {
        //从redis查询点赞过blog的用户id
        String key = BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok();
        }
        List<Long> idList = top5.stream().map(Long::valueOf).collect(Collectors.toList());


        //根据用户id查询用户信息
        String ids = StrUtil.join(",", idList);
        List<UserDTO> userDTOs = userService
                .query().in("id", idList).last("order by field (id," + ids + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());


        return Result.ok(userDTOs);
    }

    /**
     * 保存blog,同时推送给关注的人
     *
     * @param blog
     * @return
     */
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO userDTO = UserHolder.getUser();
        blog.setUserId(userDTO.getId());
        // 保存探店博文
        boolean success = save(blog);

        //找出是谁关注了该用户，List<Follow>
        List<Follow> followList = followService.query().eq("follow_user_id", userDTO.getId()).list();
        //将笔记推送给所有粉丝

        for (Follow follow : followList) {
            //获取粉丝id
            Long userId = follow.getUserId();
            String key = FEED_KEY + userId;
            //推送
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 滚动分页查询收件箱
     *
     * @param max
     * @param offset
     * @return
     */
    public Result getFeed(Long max, Integer offset) {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();

        //2.获取redis的推送消息
        String key = FEED_KEY + userId;

        Set<ZSetOperations.TypedTuple<String>> tupleSet =
                stringRedisTemplate.opsForZSet()
                        .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (tupleSet == null || tupleSet.isEmpty()) {
            return Result.ok();
        }
        //3.解析数据 blogId 、分数（时间戳）、offset时间戳最小值重复值数、minTime推送的最小时间戳
        ArrayList<Long> blogIdList = new ArrayList<>();
        int count = 1;//offset时间戳最小值重复值数
        Long minTime = 0L;//推送的最小时间戳

        for (ZSetOperations.TypedTuple<String> tuple : tupleSet) {
            blogIdList.add(Long.valueOf(tuple.getValue()));

            Long time = tuple.getScore().longValue();
            if(minTime.equals(time)){
                count++;
            }else {
                minTime = time;
                count = 1;
            }
        }

        /*List<Long> blogIdList = tupleSet
                .stream()
                .map(t -> Long.valueOf(t.getValue()))
                .collect(Collectors.toList());

        List<Long> timeList = tupleSet
                .stream()
                .map(t -> t.getScore().longValue())
                .collect(Collectors.toList());

        int count = 1;//offset时间戳最小值重复值数
        Long minTime = timeList.get(timeList.size() - 1);//推送的最小时间戳

        for (int i = timeList.size() - 2; i >= 0; i--) {
            if(Objects.equals(minTime, timeList.get(i))){
                count++;
            }else break;
        }*/
        //4.根据blogId查询blog
        String idStr = StrUtil.join(",",blogIdList);
        List<Blog> blogList = query()
                .in("id", blogIdList)
                .last("order by field (id," + idStr + ")").list();
        //4.1对每个blog进行处理，是否点赞、是那个用户发出的blog
        blogList.forEach(this::getBlogUser);

        //4.封装数据
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(count);
        scrollResult.setMinTime(minTime);

        //5.返回
        return Result.ok(scrollResult);
    }
}
